<?php

namespace app\common\model;


use app\common\exception\ApiException;
use think\Log;

class Article extends BaseModel {
    public function image() {
        return $this->hasOne('Images', 'id', 'img_id')->field('id,url,from');
    }

    public function getArticleList($condition, $from = 0, $size = 10, $order = []) {
        $order['id'] = 'desc';
        if (empty($condition['status']) && !isset($condition['status'])) {
            $condition['status'] = ['neq', config('code.status_delete')];
        }
        $result = $this
            ->with(['image'])
            ->where($condition)->order($order)
            ->limit($from, $size)
            ->select();
        if (!$result) {
            throw new ApiException('没有数据了', 200, 1);
        }
        if (input('get.total') == 1) {
            $arr['list']  = collection($result)->hidden(['img_id', 'update_time', 'content', 'image.id', 'image.from']);
            $arr['total'] = $this->where($condition)->count();
            $result       = $arr;
            return $result;
        }
        return collection($result)->hidden(['img_id', 'update_time', 'content', 'image.id', 'image.from']);
    }

    public function getArticleItem($id) {
        $result = $this
            ->with(['image'])
            ->where(['id' => $id])
            ->find();
        if (!$result) {
            throw new ApiException('获取失败', 200, config('code.fail'));
        }
        return collection([$result])->hidden(['image.id', 'image.from', 'update_time', 'view_count', 'comment_count', 'status']);
    }

    public function getArticleDetail($id) {
        $result = $this->with(['image'])
            ->where(['id' => $id])
            ->find();
        if (!$result) {
            throw new ApiException('获取失败', 200, config('code.fail'));
        }
        return $result;
    }

    public function updateCount($id, $field, $type = false) {
        if (!$type) {
            $this->get($id)->setInc($field);
        } else {
            $this->get($id)->setDec($field);
        }
    }
}